from fastapi import APIRouter, Depends, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.database.session import get_db
from app.services.auth import AuthService
from app.schemas.user import UserCreate, User, Token, UserLogin
from app.api.dependencies import get_current_user

router = APIRouter(
    prefix="/auth",
    tags=["认证"]
)

@router.post("/register", response_model=User, status_code=status.HTTP_201_CREATED)
def register(user_in: UserCreate, db: Session = Depends(get_db)):
    """用户注册"""
    return AuthService.register_user(db, user_in)

@router.post("/login", response_model=Token)
def login(
    db: Session = Depends(get_db),
    form_data: OAuth2PasswordRequestForm = Depends()
):
    """用户登录，使用OAuth2密码模式"""
    user_in = UserLogin(username=form_data.username, password=form_data.password)
    access_token = AuthService.login_user(db, user_in)
    return {"access_token": access_token, "token_type": "bearer"}

@router.post("/logout", status_code=status.HTTP_200_OK)
def logout(current_user: User = Depends(get_current_user)):
    """用户登出"""
    success = AuthService.logout_user(current_user.id)
    return {"message": "成功登出" if success else "登出失败"}

@router.get("/me", response_model=User)
def read_current_user(current_user: User = Depends(get_current_user)):
    """获取当前登录用户信息"""
    return current_user
